package vl07.network;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.*;
import java.net.*;
import java.util.Date;

import javax.swing.*;

public class Browser2 extends JFrame {
	private JLabel lblUrl;
	private JTextField txtUrl;
	private JButton btnGo;
	private JScrollPane paneInhalt;
	private JTextArea txtInhalt;

	public static void main(String[] args) {
		new Browser2();
	}

	/** Creates new form Browser1 */
	public Browser2() {
		super("Browser2");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());

		Box topBox = Box.createHorizontalBox();
		this.add(topBox, BorderLayout.NORTH);

		lblUrl = new JLabel("URL");
		lblUrl.setText("URL");
		topBox.add(lblUrl);

		txtUrl = new JTextField();
		txtUrl.setText("http://www.google.com/");
		txtUrl.setPreferredSize(new java.awt.Dimension(400, 21));
		topBox.add(txtUrl);

		topBox.add(Box.createHorizontalStrut(30));
		
		btnGo = new JButton("Go");
		topBox.add(btnGo);
		btnGo.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				browse();
			}
		});

		paneInhalt = new JScrollPane();
		paneInhalt.setPreferredSize(new java.awt.Dimension(600, 300));
		txtInhalt = new JTextArea();
		txtInhalt.setFont(new java.awt.Font("Courier New", 0, 12));
		paneInhalt.setViewportView(txtInhalt);
		this.add(paneInhalt, BorderLayout.CENTER);

		pack();
		setVisible(true);
	}

	private void browse() {
		URL url;
		URLConnection inConnection = null;
		StringBuffer headers = new StringBuffer();
		BufferedReader inReader = null;
		String lineIn;
		StringBuffer urlInhalt = new StringBuffer();

		// Network errors are always possible
		try {
			// Same as Browser 1
			url = new URL(txtUrl.getText());
			
			// Get a URLConnection from the URL. This provides more
			// features, like access to the header information
			inConnection = url.openConnection();
			headers.append("Content encoding: " + inConnection.getContentEncoding() + "\n");
			headers.append("Content type: " + inConnection.getContentType() + "\n");
			headers.append("Last modified: " + new Date(inConnection.getLastModified()).toString() + "\n\n");
			
			if (inConnection instanceof HttpURLConnection) {
				HttpURLConnection in_http = (HttpURLConnection) inConnection;
				headers.append("HTTP Status-Code: " + in_http.getResponseCode() + "\n\n");
			}

			InputStream in1 = inConnection.getInputStream();
			InputStreamReader in2 = new InputStreamReader(in1);
			inReader = new BufferedReader(in2);
			while ((lineIn = inReader.readLine()) != null) {
				urlInhalt.append(lineIn + "\n");
			}

			// Show the result in "txtInhalt"
			txtInhalt.setText(headers.toString() + urlInhalt.toString());
		}

		// If an error occurred, show the error message in txtInhalt
		catch (Exception err) {
			txtInhalt.setText("ERROR: " + err.toString());
		}
		finally {
			try {
				if (inReader != null) inReader.close();
			} catch (IOException e) {
			}
		}
	}
}
